package com.qiantu.phone.widget.setting;

import static android.app.Activity.RESULT_OK;
import static android.util.TypedValue.COMPLEX_UNIT_PX;

import static com.qiantu.api.entity.RoomBean.ROOM_COMMON_SERIALNO;

import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.base.BaseActivity;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceDetailChangeEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.ui.activity.SelectFloorRoomActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class DeviceSettingArea extends SettingBar implements View.OnClickListener {
    private DeviceBean mDevice;
    private AppActivity mContext;
    public DeviceSettingArea(AppActivity context, DeviceBean deviceBean) {
        this(context, null, deviceBean);
    }

    public DeviceSettingArea(AppActivity context, AttributeSet attrs, DeviceBean deviceBean) {
        this(context, attrs, 0, deviceBean);
    }

    public DeviceSettingArea(AppActivity context, AttributeSet attrs, int defStyleAttr, DeviceBean deviceBean) {
        this(context, attrs, defStyleAttr, R.style.setting_item_style, deviceBean);
    }

    public DeviceSettingArea(@NonNull AppActivity context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes, DeviceBean deviceBean) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mDevice = deviceBean;
        mContext = context;
        setLeftText(R.string.affiliation_room);
        if(mDevice.getLinkType() == 3){
            setRightText(mDevice.getFloorName());
        }else{
            setRightText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(mDevice.getRoomSerialNo()));
        }
        setRightTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setRightTextSize(COMPLEX_UNIT_PX, DensityUtils.dip2px(context, 12));
        setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getContext(), SelectFloorRoomActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("title", getResources().getString(R.string.affiliation_room));
        intent.putExtra("linkType",mDevice.getLinkType());
        if(mDevice.getLinkType() == 3){
            intent.putExtra("roomSerialNo", mDevice.getFloorSerialNo());
        }else{
            intent.putExtra("roomSerialNo", mDevice.getRoomSerialNo());
        }
        mContext.startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
            @Override
            public void onActivityResult(int resultCode, Intent data) {
                if (resultCode == RESULT_OK) {
                    String serialNo = data.getStringExtra("serialNo");
                    String roomName = data.getStringExtra("roomName");
                    String floorSerialNo = data.getStringExtra("floorSerialNo");
                    String floorName = data.getStringExtra("floorName");
                    changeRoom(serialNo, roomName, floorSerialNo,floorName);
                }
            }
        });
    }

    private void changeRoom(String serialNo, String roomName, String floorSerialNo,String floorName) {
        Map data = new HashMap<>();
        //1房间绑定 2房屋绑定(移除房间,绑定到房屋)
        int linkType = 0;
        if (ROOM_COMMON_SERIALNO.equals(serialNo)) {
            linkType = 2;
            data.put("targetSerialNo", AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
        }else  if(floorSerialNo.equals(serialNo)){
            linkType = 3;
            data.put("targetSerialNo", floorSerialNo);
        } else {
            linkType = 1;
            data.put("targetSerialNo", serialNo);
        }
        data.put("type", linkType);
        List<String> selectedSerialNos = new ArrayList<>();
        selectedSerialNos.add(mDevice.getDeviceSerialNo());
        int finalLinkType = linkType;
        HttpCallback<HttpData<Void>> callback = new HttpCallback<HttpData<Void>>(mContext) {
            @Override
            public void onStart(Call call) {
                mContext.showDialog(null);
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                if (result.isRequestSucceed()) {
                    mDevice.setLinkType(finalLinkType);
                    if(finalLinkType == 3){
                        mDevice.setRoomSerialNo("");
                        mDevice.setRoomName("");
                    }else{
                        mDevice.setRoomSerialNo(serialNo);
                        mDevice.setRoomName(roomName);
                    }
                    if(TextUtils.isEmpty(floorSerialNo)){
                        mDevice.setFloorName(null);
                        mDevice.setFloorSerialNo(null);
                        setRightText(roomName);
                    }else{
                        mDevice.setFloorSerialNo(floorSerialNo);
                        mDevice.setFloorName(floorName);
                        setRightText(mDevice.getFloorName() + mDevice.getRoomName());
                    }
                    LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                    EventBus.getDefault().post(new RefreshDeviceListEvent());
                    EventBus.getDefault().post(new RefreshFloorRoomEvent());
                    EventBus.getDefault().post(new DeviceDetailChangeEvent(mDevice.getDeviceSerialNo()));

                    mContext.toast(R.string.set_success);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        };
        if(mDevice.getDeviceGroup() == 0){
            data.put("deviceSerialNoList", selectedSerialNos);
            LLHttpManager.deviceBelong(mContext, data,callback);
        }else{
            data.put("deviceGroupSerialNos", selectedSerialNos);
            LLHttpManager.deviceGroupBelong(mContext, data,callback);
        }
    }
}
